import java.util.ArrayList;
import java.util.List;

/**
 * 将一个给定字符串 s 根据给定的行数 numRows ，以从上往下、从左到右进行 Z 字形排列。
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.convert("PAYPALISHIRING", 3)); //PAHNAPLSIIGYIR
        System.out.println(solution.convert("PAYPALISHIRING", 4)); //PINALSIGYAHRPI
    }

    public String convert(String s, int numRows) {
        if (numRows == 1) {
            return s;
        }

        List<StringBuilder> list = new ArrayList<>(numRows);
        for (int i = 0; i < numRows; i++) {
            list.add(new StringBuilder());
        }

        boolean isAdd = true;
        int limit = numRows - 1;
        int cur = 0;

        for (char c : s.toCharArray()) {
            list.get(cur).append(c);

            if (isAdd) {
                if (cur == limit) {
                    cur--;
                    isAdd = false;
                } else {
                    cur++;
                }
            } else {
                if (cur == 0) {
                    cur++;
                    isAdd = true;
                } else {
                    cur--;
                }
            }
        }

        StringBuilder result = new StringBuilder();
        for (StringBuilder sb : list) {
            result.append(sb);
        }
        return result.toString();
    }

}